package com.axjy.controller;

import com.axjy.pojo.Role;
import com.axjy.pojo.User;
import com.axjy.service.RoleService;
import com.axjy.util.Log;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/sys/role")
public class RoleController {

    @Resource
    private RoleService roleService;

    private String msg;


    @GetMapping("/list")
    public List<Role> list(){
        List<Role> list=roleService.list();
        return list;
    }


    @PostMapping("/add")
    public String add(Role role, HttpSession session){
       User loginUser= (User) session.getAttribute("loginUser");
       if(loginUser!=null){
           role.setModifyBy(loginUser.getUsername());
       }
       role.setModifyTime(LocalDateTime.now());
        try{
            roleService.add(role);
            msg="角色添加成功！";
        }catch (Exception ex){
            msg="角色添加失败！";
            Log.logger.error(msg,ex);
        }
        return msg;
    }

    @PostMapping("/update")
    public String update(Role role, HttpSession session){
        User loginUser= (User) session.getAttribute("loginUser");
        if(loginUser!=null){
            role.setModifyBy(loginUser.getUsername());
        }
        role.setModifyTime(LocalDateTime.now());
        try{
            roleService.update(role);
            msg="角色修改成功！";
        }catch (Exception ex){
            msg="角色修改失败！";
            Log.logger.error(msg,ex);
        }
        return msg;
    }

    @GetMapping("/del")
    public String del(Integer id){
        try{
            roleService.del(id);
            msg="角色删除成功！";
        }catch (Exception ex){
            msg="角色删除失败！该角色正在被其他用户引用！";
            Log.logger.error(msg,ex);
        }
        return msg;
    }


}
